package org.example.struct.array2;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author liyishan
 * @date 2023/10/26 10:58
 * @apiNote
 */

public class Test00945MinIncrementForUnique {

    public static void main(String[] args) {
        int[] nums = {3,2,1,2,1,7};
        System.out.println(minIncrementForUnique(nums));
    }
    public static int test1(int[] nums) {
        Arrays.sort(nums);
        int ans =0,taken =0;
        for(int i=1;i<nums.length;i++){
            if(nums[i] == nums[i-1]){
                taken ++;
                ans -=nums[i];
            }else{
                int give = Math.min(taken,nums[i] -nums[i-1]-1);
                ans += give *(give+1)/2 +give * nums[i-1];
                taken -= give;
            }
        }
        if(nums.length>0){
            ans += taken *(taken+1)/2 +taken * nums[nums.length-1];
        }
        return ans;
    }

    public static int test2(int[] nums) {
        Arrays.sort(nums);
        int move = 0;
        // 遍历数组，若当前元素小于等于它的前一个元素，则将其变为前一个数+1
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] <= nums[i - 1]) {
                int pre = nums[i];
                nums[i] = nums[i - 1] + 1;
                move += nums[i] - pre;
            }
        }
        return move;
    }
    //-------------------------------超时-------------------------------------------
    public static int test(int[] nums) {
        Arrays.sort(nums);
        Set<Integer> set = new HashSet<>();
        set.add(nums[0]);
        int res = 0;
        for(int i = 1; i < nums.length; i++){
            while(set.contains(nums[i])){
                nums[i]++;
                res++;
            }
            set.add(nums[i]);
        }
        return res;
    }


   //线性探测法
    public static int minIncrementForUnique(int[] nums) {
        int[] pos = new int[80000];
        Arrays.fill(pos,-1);
        int move = 0;
        for(int num : nums){
            int b = findPos(num,pos);
            move += b-num;
        }
        return move;
    }

    private static int findPos(int num,int[] pos){
        int b =pos[num];
        if(b == -1){
            pos[num] = num;
            return num;
        }
        b = findPos(b+1,pos);
        pos[num] = b;
        return b;
    }


}
